package game.util;

import java.awt.Point;

import org.newdawn.slick.Input;

import shared.Tiles;
import shared.io.game.Player;
import shared.io.game.Room;

import game.Game;

public class MovementModule {

   /**
    * Possible movement keys.
    */
   private final int[] KEYS = new int[] {
         Input.KEY_UP, Input.KEY_RIGHT, Input.KEY_DOWN, Input.KEY_LEFT};
   private Game game;
   
   public MovementModule(Game game) {
      this.game = game;
   }
   
   /**
    * Checks if keys have been pressed.
    */
   public void update(Input input) {
      for (int dirKey : KEYS) {
         if (input.isKeyPressed(dirKey) || input.isKeyDown(dirKey)) {
            move(dirKey);
            return;
         }
      }
   }
   
   /**
    * Moves player in direction.
    */
   private void move(int direction) {
      Room room = getRoom(direction);
      if (room == null || room.getTile() == Tiles.WALL) {
         return;
      }
      game.getPlayer().setLoc(room.getLoc().x, room.getLoc().y);
      game.getSession().writeObject(game.getPlayer().getLoc());
   }
   
   /**
    * Gets next room in direction from player.
    */
   private Room getRoom(int direction) {
      Point point = game.getPlayer().getLoc();
      switch (direction) {
      case Input.KEY_UP:
         point.y -= 1;
         break;
      case Input.KEY_RIGHT:
         point.x += 1;
         break;
      case Input.KEY_DOWN:
         point.y += 1;
         break;
      case Input.KEY_LEFT:
         point.x -= 1;
         break;
      }
      for (Room room : game.getRooms()) {
         synchronized (room) {
            if (room.getLoc().equals(point)) {
               return room;
            }
         }
         
      }
      return null;
   }
   
}
